/**
 * Created by Junhua on 2019/5/7.
 */
const Router = require('koa-router')
const jwt = require('jsonwebtoken')
const { query,constInsert,constUpdate,exeTrans } = require('../db')
const { getRes } = require('../res')
const { formatDate,pay_info,randomWord } = require('../util')
const nodemailer = require("nodemailer")
const send = require('koa-send');
let paytool = require('../paytools')
let request = require('request');
var fs = require('fs');

let login = new Router()

login.post('/', async(ctx) => {//登录接口
    console.log('***********************************8')
    let qry = ctx.request.body;
    let sql = `select u.id,u.name,u.mail,u.status,u.lasttime from userinfo u
                where u.mail=? and u.pwd=? and u.status>=0`;
    try{
        let res = await query(sql,[qry.mail,qry.pwd]);
        if(res.length == 0) return ctx.response.body = getRes(1);//登录失败
        let obj = {
            id :res[0].id,
            mail:res[0].mail,
            status:res[0].status,
            name:res[0].name,
            lasttime:res[0].lasttime
        }
        let token = jwt.sign(obj, 'qi_secret_sheng', {expiresIn: 60 * 60 * 24 * 365});
        console.log(token);

        let user = {
            mail:res[0].mail,
            id:res[0].id,
            token:token
        };

        let usql = "select u.mail,u.lasttime from userinfo u where u.id=? and u.lasttime>now() and u.status>=0";
        let tmp = await query(usql,user.id);

        if(tmp.length>0){
            user.is_vip = 1;
            user.lasttime = tmp[0].lasttime;
        }

        ctx.response.body = getRes(0,user);
    }catch (e){
        console.log(e);
        ctx.response.body = getRes(2);
    }
})

login.post('/register', async(ctx) => {//登录接口
    try{
        console.log('***********************************8');
        let qry = ctx.request.body;
        let sql = `select count(1) as cnt from userinfo where mail=?`;
        let total = await query(sql,qry.mail);
        if(total[0].cnt>0) return ctx.response.body = getRes(4);
        userinfo = {
            mail:qry.mail,
            pwd:qry.pwd
        }
        let token = jwt.sign(userinfo, 'qi_secret_sheng', {expiresIn: 60 * 15});
        console.log(token);
        //设置邮箱配置
        let jpeg = ``;
        let html = "<div>你好，<a href=\"http://106.53.124.171:5002/api/user/register_toke?token="+token+"\" rel=\"noopener\" target=\"_blank\">请点击我认证</a></div><div><img src=\"data:image/jpeg;base64,"+jpeg+"\" alt=\"\"></div>";
        let info =  await sendMailTo("零柒知乎插件注册认证邮件",qry.mail,html);
        ctx.response.body = getRes(5);
    }catch (e){
        console.log(e);
        ctx.response.body = getRes(2);
    }
});

login.post('/forgetpassword', async(ctx) => {//
    try{
        console.log('***********************************8');
        let qry = ctx.request.body;
        let sql = `select count(1) as cnt from userinfo where mail=?`;
        let total = await query(sql,qry.mail);
        if(total[0].cnt==0) return ctx.response.body = getRes(9);

        let sqlnum = `select count(1) as cnt from seccode u where u.mail=? and TIMESTAMPDIFF(MINUTE,u.creattime,now())<15 and u.status=0`;
        let totalnum = await query(sqlnum,qry.mail);
        if(totalnum[0].cnt>0) return ctx.response.body = getRes(10);

        let seccode = randomWord(6);
        let date = new Date();
        let codeinfo = {
            mail:qry.mail,
            seccode:seccode,
            status:0,
            creattime:date
        }
        await constInsert('seccode',codeinfo);
        //设置邮箱配置
        let jpeg = ``;

        let html = "<div>你好，重置密码的验证码为"+seccode+"</div><div><img src=\"data:image/jpeg;base64,"+jpeg+"\" alt=\"\"></div>";
        let info =  await sendMailTo("零柒知乎插件密码重置验证码",qry.mail,html);
        ctx.response.body = getRes(5);
    }catch (e){
        console.log(e);
        ctx.response.body = getRes(2);
    }
});

login.post('/updatepassword', async(ctx) => {//
    try{
        console.log('***********************************8');
        let qry = ctx.request.body;
        let sql = `select count(1) as cnt from userinfo where mail=?`;
        let total = await query(sql,qry.mail);
        if(total[0].cnt==0) return ctx.response.body = getRes(9);

        let sqlnum = `select count(1) as cnt from seccode u where u.mail=? and u.seccode=? and TIMESTAMPDIFF(MINUTE,u.creattime,now())<15 and u.status=0`;
        let totalnum = await query(sqlnum,[qry.mail,qry.seccode]);
        if(totalnum[0].cnt==0) return ctx.response.body = getRes(11);

        let updatesql = `update userinfo set pwd=? where mail=?`;
        let res = await query(updatesql,[qry.pwd,qry.mail]);
        let updatesqlnum = `update seccode u set u.status=1 where u.mail=? and u.seccode=?`;
        let ress = await query(updatesqlnum,[qry.mail,qry.seccode]);

        ctx.response.body = getRes(0);
    }catch (e){
        console.log(e);
        ctx.response.body = getRes(2);
    }
});


//支付回调接口
login.post('/paynotify', async(ctx) => {
    try{
        let tranFunc = async (conn) => {//执行事务
            try {
                let err_res = {
                    return_code : 'FAIL',
                    return_msg : ''
                }
                let qry = ctx.request.body;
                console.log(qry);
                if(!paytool.notifyCheck(qry)){
                    return Promise.resolve(err_res);
                }
                if(qry.return_code!='1'){
                    return Promise.resolve(err_res);
                }

                let payjs_order_id = qry.payjs_order_id;

                let sql = `select * from pay where payjs_order_id = ?`;
                let pay = await query(sql,payjs_order_id);

                if(pay.length==0 || pay[0].status!=0){
                    return Promise.resolve(err_res);
                }
                

                let usql = "select u.* from userinfo u where u.id=?";
                let user = await query(usql,pay[0].user_id);

                if(user.length==0){
                    return Promise.resolve(err_res);
                }

                let lasttime = user[0].lasttime;
                let date = new Date();
                if(lasttime==null){
                    date.setMonth(date.getMonth()+pay[0].month); 
                    lasttime = date;
                }else if(lasttime<date){
                    date.setMonth(date.getMonth()+pay[0].month); 
                    lasttime = date;
                }else{
                    date = new Date(lasttime);
                    date.setMonth(date.getMonth()+pay[0].month); 
                    lasttime = date;
                }
                console.log(lasttime);
                user[0].lasttime = formatDate(lasttime,"yyyy-MM-dd hh:mm:ss");

                pay[0].status=1;
                await constUpdate("pay",pay[0]);
                await constUpdate("userinfo",user[0]);

                err_res = "success";
                return Promise.resolve(err_res);
            }catch (e){
                return Promise.reject(e);
            }
        }
        let r = await exeTrans(tranFunc);
        
        ctx.response.body = r;
    }catch (e){
        let err_res = {
            return_code : 'FAIL',
            return_msg : ''
        }
        console.log(e);
        ctx.response.body = err_res;
    }
});

//收费按钮
login.post('/pay_info', async(ctx) => {
    try{

        let data = pay_info();

        ctx.response.body = getRes(0,data);
    }catch (e){
        console.log(e);
        ctx.response.body = err_res;
    }
});

async function sendMailTo(subject,mailUserName, mailContent){
  
    let transporter = nodemailer.createTransport({
        host: "smtp.163.com",
        port: 465,
        secure: true, // true for 465, false for other ports
        auth:{
            user:'15989082884@163.com',
            pass:'密码'
        }
    });
  
    // setup email data with unicode symbols
    let mailOptions = {
        from: '零柒知乎插件的邮箱 <15989082884@163.com>', // sender address
        to: `${mailUserName}`, // list of receivers
        subject: `${subject}`, // Subject line
        html: mailContent // html body
    };
  
    // send mail with defined transport object
    let info = await transporter.sendMail(mailOptions);
  
    console.log("Message sent: %s", info.messageId);
    
    return info;
}


module.exports = login;